import { createSlice } from "@reduxjs/toolkit";
import { Toast } from "antd-mobile";

// 创建切片
const TickPersonSlice = createSlice({
    name: "TickPersonSlice", //用户标记slice的名词
    // 定义初始状态
    initialState: {
        tickPersonList: [
            {
                id: 1,
                name: "迪丽热巴",
                code: "411381199908206666",
                state: false,
            },
            {
                id: 2,
                name: "刘强东",
                code: "311381198404158888",
                state: false,
            },
            {
                id: 3,
                name: "印度阿三",
                code: "011381199507233321",
                state: false,
            },
            {
                id: 4,
                name: "巴铁小伙",
                code: "211021200009047893",
                state: false,
            },
        ],
    },
    // 定义reducer
    reducers: {
        //修改乘车人状态
        stateChange(state, { payload }) {
            const item = state.tickPersonList.find((item) => item.id === payload.id);
            if (item) {
                item.state = !item.state;
            }
        },
        //删除乘车人
        delPer(state, { payload }) {
            //过滤掉要删除的乘车人
            state.tickPersonList = state.tickPersonList.filter(
                (item) => item.id !== payload.id
            );
        },
        //添加乘车人
        addPer(state, { payload }) {
            const item = state.tickPersonList.find((item) => item.id === payload.id);
            if (!item) {
                state.tickPersonList.push(payload);
                Toast.show({
                    icon: "success",
                    content: "添加成功",
                });
            } else {
                Toast.show({
                    icon: "fail",
                    content: "此人已存在",
                });
            }
        },
        //修改乘车人
        editPer(state, { payload }) {
            const item = state.tickPersonList.find((item) => item.id === payload.id);
            if (item) {
                Object.assign(item, payload);
                Toast.show({
                    icon: "success",
                    content: "修改成功",
                });
            }
        },
    },
});

// 导出action
export const { stateChange, delPer, addPer, editPer } = TickPersonSlice.actions;

// 导出reducer
export default TickPersonSlice.reducer;
